import { routerRedux } from 'dva/router';
import { queryNotices } from '../services/api';
import { queryMenuList } from '../services/user';
import { getAuthority } from '../utils/authority';

export default {
  namespace: 'global',

  state: {
    collapsed: false,
    notices: [],
    menuList: [],
  },

  effects: {
    *fetchNotices(_, { call, put }) {
      const data = yield call(queryNotices);
      yield put({
        type: 'saveNotices',
        payload: data,
      });
      yield put({
        type: 'user/changeNotifyCount',
        payload: data.length,
      });
    },
    *clearNotices({ payload }, { put, select }) {
      yield put({
        type: 'saveClearedNotices',
        payload,
      });
      const count = yield select(state => state.global.notices.length);
      yield put({
        type: 'user/changeNotifyCount',
        payload: count,
      });
    },

    *fetchAuthority(_, { call, put }) {
      // 判断用户是否登录
      const Authority = getAuthority();
      if (Authority === '' || Authority === null || Authority === undefined) {
        yield put(routerRedux.push('/user/login'));
        return;
      }

      // 判断本地是否有菜单
      const menuList = localStorage.getItem('menu');
      if(menuList === null || menuList === undefined){
        const response = yield call(queryMenuList, { role: Authority });
        if (response.status) {
          yield put({
            type: 'saveMenuList',
            payload: JSON.parse(response.data.menu),
          });
          localStorage.setItem('menu', response.data.menu);
        } else {
          yield put(routerRedux.push('/user/login'));
        }
      }

      // 根据用户权限跳转到固定的页面
      if(Authority === 'student'){
        yield put(routerRedux.push('/center/studentinfor'));
      } else {
        yield put(routerRedux.push('/center/teacherinfor'));
      }
    },
  },

  reducers: {
    changeLayoutCollapsed(state, { payload }) {
      return {
        ...state,
        collapsed: payload,
      };
    },
    saveNotices(state, { payload }) {
      return {
        ...state,
        notices: payload,
      };
    },
    saveClearedNotices(state, { payload }) {
      return {
        ...state,
        notices: state.notices.filter(item => item.type !== payload),
      };
    },
    saveMenuList(state, { payload }) {
      return {
        ...state,
        menuList: payload,
      };
    },
  },

  subscriptions: {
    setup({ history, dispatch }) {
      dispatch({ type: 'fetchAuthority' });
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return history.listen(({ pathname, search }) => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
      });
    },
  },
};
